//
//  ZZShareCardController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/14.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZShareCardController.h"
#import "UIView+Border.h"
#import "ZZShareView.h"
#import "ZCTTMLEmojiLabel.h"
#import "UserInfoController.h"
#import "SVWebViewController.h"

@interface ZZShareCardController ()<ZZTopicCellDelegate,ZCTTMLEmojiLabelDelegate>

@property(nonatomic,strong) UIScrollView *contentView;

@end

@implementation ZZShareCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // Do any additional setup after loading the view.
    self.navigationItem.title =@"分享卡片";// convertToString(_entity.user_name);
    [self setNavigationBar];
    
    
    self.navigationController.navigationBarHidden = NO;
    
    _contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 44 - (ZC_iPhoneX ? 38:0))];
    [_contentView setBackgroundColor:UIColor.whiteColor];
    _contentView.alwaysBounceVertical = NO;
    _contentView.alwaysBounceHorizontal = NO;
    [self.view addSubview:_contentView];
    
    
    [self createHeaderView];
    
    [self crateFooterView];
    
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - NavBarHeight - 44 - (ZC_iPhoneX ? 38:0), ScreenWidth, 44)];
    [footerView setBackgroundColor:UIColor.whiteColor];
    [footerView addTopBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    
    [footerView addSubview:[self createBtmBtn:1]];
    [footerView addSubview:[self createBtmBtn:2]];
    
    [self.view addSubview:footerView];
    
}

-(void)btmClick:(UIButton * )btn{
    UIImage *img = [self drawToContext:self.contentView];
    
    if(btn.tag == 1){
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    }else{
        ZZShareView *shere = [[ZZShareView alloc] initWithShareType:ZZShareTypeImage vc:self obj:img];
        [shere show];
    }
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    if(error == nil){
        [PopUtil showMessage:@"保存成功!"];
    }
}

-(UIButton *) createBtmBtn:(int ) tag{
    
    UIButton *btn = [self createButton];
    btn.tag = tag;
    [btn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [btn.titleLabel setFont:FontThirteen];
    [btn setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
    btn.frame = CGRectMake(ScreenWidth/2 * (tag - 1), 0, ScreenWidth/2, 44);
    [btn addTarget:self action:@selector(btmClick:) forControlEvents:UIControlEventTouchUpInside];
    if(tag == 1){
        [btn setImage:[UIImage imageNamed:@"icon_down"] forState:0];
        [btn setTitle:@"保存" forState:0];
    }else{
        [btn setImage:[UIImage imageNamed:@"ic_share"] forState:0];
        [btn setTitle:@"分享" forState:0];
    }
    return btn;
}

- (UIImage*)drawToContext:(UIView*)view{
    
    //1.开启上下文
    UIGraphicsBeginImageContext(view.frame.size);
    
    //2.绘制图形
    CGContextRef ctx =UIGraphicsGetCurrentContext();
    
    //把layer上的内容绘制到上下文当中
    
    [view.layer renderInContext:ctx];
    
    UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();

    //3.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

-(void)createHeaderView{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavBarHeight - 164 - 44 - (ZC_iPhoneX?38:0))];
    [headerView setBackgroundColor:UIColor.whiteColor];
    [headerView addTopBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    
    UIImageView *imgView = [self createImageView];
    [imgView setFrame:CGRectMake(20, 20, 44, 44)];
    imgView.layer.cornerRadius = 22.0f;
    imgView.layer.masksToBounds = YES;
    [imgView sd_setImageWithURL:[NSURL URLWithString:convertToString(_replyModel.user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [headerView addSubview:imgView];
    
    
    UILabel *labName = [self createLabel];
    [labName setFrame:CGRectMake(74, 21, ScreenWidth - 84 - 40, 21)];
    [labName setText:_replyModel.user_info.user_name];
    [headerView addSubview:labName];
    
    UILabel *labDesc = [self createLabel];
    [labDesc setFrame:CGRectMake(74, 41, ScreenWidth - 84 - 40, 21)];
    [labDesc setTextColor:UIColorFromRGB(Text6Color)];
    [labDesc setText:@"发布了一条评论"];
    [headerView addSubview:labDesc];
    
    [self createCode:headerView];
    
    CGFloat ch = ScreenHeight - 164 - 44 - (ZC_iPhoneX?38:0) - 84 - NavBarHeight;
    
    ZCTTMLEmojiLabel *labContent = [self createLinkLabel:CGRectMake(20, 84, ScreenWidth - 40, ch)];
    [self addLinkMessage:labContent text:convertToString(_replyModel.message)];
    [headerView addSubview:labContent];
    
    
    [_contentView addSubview:headerView];
}

-(void)crateFooterView{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - NavBarHeight - 164 - 44 - (ZC_iPhoneX?38:0), ScreenWidth, 154)];
    [footerView setBackgroundColor:UIColor.whiteColor];
    [footerView addTopBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    
    UIImageView *imgLine = [self createImageView];
    [imgLine setBackgroundColor:UIColorFromRGB(BgLineColor)];
    [imgLine setFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [footerView addSubview:imgLine];
    
    UILabel *labDesc = [self createLabel];
    [labDesc setFrame:CGRectMake(20, 30, ScreenWidth - 40, 21)];
    [labDesc setTextColor:UIColorFromRGB(Text6Color)];
    [labDesc setFont:FontThirteen];
    [labDesc setText:@"长按参与评论"];
    [footerView addSubview:labDesc];
    
    UIImageView *imgView = [self createImageView];
    [imgView setFrame:CGRectMake(20, 63, 90, 90)];
    imgView.layer.cornerRadius = 3.0f;
    imgView.layer.masksToBounds = YES;
    [imgView sd_setImageWithURL:[NSURL URLWithString:convertToString([self getShareMesage][@"avatar"])] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [footerView addSubview:imgView];
    
    
    UILabel *labName = [self createLabel];
    [labName setFrame:CGRectMake(120, 63, ScreenWidth - 140, 90)];
    [labName setTextColor:UIColorFromRGB(Text6Color)];
    
    [labName setText:[self getShareMesage][@"title"]];
    [footerView addSubview:labName];
    
    
    [_contentView addSubview:footerView];
    
}

-(NSDictionary *) getShareMesage{
    NSString *avatarUrl = @"";
    NSString *url = @"";
    NSString *title = @"";
    if(_forum!=nil){
        avatarUrl = _forum.user_info.user_avatar;
        title = _forum.title;
        url = _forum.share_url;
    }else{
        avatarUrl = _model.user_info.user_avatar;
        title = _model.title;
        url = _model.share_url;
    }
    return @{@"share":url,@"avatar":avatarUrl,@"title":title};
}


-(void)createCode:(UIView *) header{
    //1. 实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2. 恢复滤镜的默认属性
    [filter setDefaults];
    // 3. 将字符串转换成NSData
    NSString *urlStr = convertToString([self getShareMesage][@"share"]);
    NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
    // 4. 通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKey:@"inputMessage"];
    // 5. 获得滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    
    UIImageView *imgCode = [self createImageView];
    [imgCode setFrame:CGRectMake(ScreenWidth - 60, 22, 40, 40)];
    
    // 6. 将CIImage转换成UIImage，并显示于imageView上 (此时获取到的二维码比较模糊,所以需要用下面的createNonInterpolatedUIImageFormCIImage方法重绘二维码)
    imgCode.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:40];//重绘二维码,使其显示清晰
    [header addSubview:imgCode];
}

/**
 * 根据CIImage生成指定大小的UIImage
 *
 * @param image CIImage
 * @param size 图片宽度
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}



#pragma mark - gesture delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"ZCTTMLEmojiLabel"]) {
        return NO;
    }
    return YES;
    
}

-(ZCTTMLEmojiLabel *)createLinkLabel:(CGRect) f{
    ZCTTMLEmojiLabel *label = [[ZCTTMLEmojiLabel alloc] initWithFrame:f];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.numberOfLines = 0;
    [label setFont:FontThirteen];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setFont:[UIFont fontWithName:@"Helvetica Neue" size:30.0]];
    [label setLinkColor:UIColorFromRGB(TextLinkColor)];
    [label setDelegate:self];
    label.userInteractionEnabled = YES;
    
    return label;
}

-(void)addLinkMessage:(ZCTTMLEmojiLabel *) label text:(NSString *)text{
    NSString *sugguestText = [ZZCoreTools transformStringAt:text];
    NSMutableDictionary *sugguestDict = [label getTextADict:sugguestText];
    if(sugguestDict){
        label.text = sugguestDict[@"text"];
        NSArray *sugguestArr = sugguestDict[@"arr"];
        //    [_emojiLabel setText:tempText];
        for (NSDictionary *item in sugguestArr) {
            NSString *text = item[@"htmlText"];
            int loc = [item[@"realFromIndex"] intValue];
            // 一定要在设置text文本之后设置
            [label addLinkToURL:[NSURL URLWithString:item[@"url"]] withRange:NSMakeRange(loc, text.length)];
        }
    }else{
        label.text = text;
    }
}

// 链接点击
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    DLog(@"链接地址:%@",url.absoluteString);
    [self doLinkClick:url.absoluteString];
    
}

// 链接点击
-(void)ZCMLEmojiLabel:(ZCTTMLEmojiLabel *)emojiLabel didSelectLink:(NSString *)link withType:(ZCTTMLEmojiLabelLinkType)type{
    DLog(@"意外添加的：%@",link);
    [self doLinkClick:link];
}


-(void)doLinkClick:(NSString *) url{
    if([url hasPrefix:@"name://"]){
        return;
    }
    if([url hasPrefix:@"uid://"]){
        UserInfoController *vc = [[UserInfoController alloc] init];
        vc.user_id = [url stringByReplacingOccurrencesOfString:@"uid://" withString:@""];
        [self openPushVC:vc];
    }else{
        if([url hasPrefix:@"tel:"] || validateNumber(url)){
            NSString *callURL = [url stringByReplacingOccurrencesOfString:@"tel:" withString:@""];
            [[AlertUtil shareInstance] showAlert:nil message:callURL cancelTitle:@"取消" titleArray:@[@"呼叫"] viewController:self confirm:^(NSInteger buttonTag) {
                if(buttonTag == 0){
                    // 打电话
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callURL]];
                }
            }];
        }else if([url hasPrefix:@"mailto:"] || validateEmail(url)){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }else{
            if (![url hasPrefix:@"https"] && ![url hasPrefix:@"http"]) {
                url = [@"https://" stringByAppendingString:url];
            }
            
            SVWebViewController *vc = [[SVWebViewController alloc] initWithURL:[NSURL URLWithString:url]];
            [self openPushVC:vc];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
